<template>
  <div class="page-container">
    <!-- 顶部导航栏 -->
    <div class="header">
      <el-icon :size="20" class="back-icon" @click="goBack">
        <ArrowLeft />
      </el-icon>
      <h1>系统通知</h1>
      <div class="header-right">
        <el-dropdown @command="handleCommand" v-if="notifications.length > 0">
          <span class="more-actions">
            <el-icon><MoreFilled /></el-icon>
          </span>
          <template #dropdown>
            <el-dropdown-menu>
              <el-dropdown-item command="markAllRead" v-if="unreadCount > 0">
                <el-icon><CircleCheck /></el-icon>
                全部已读
              </el-dropdown-item>
              <el-dropdown-item command="clearAll" divided>
                <el-icon><Delete /></el-icon>
                清空全部
              </el-dropdown-item>
            </el-dropdown-menu>
          </template>
        </el-dropdown>
      </div>
    </div>

    <!-- 通知列表 -->
    <div class="content">
      <div v-if="loading" class="loading-container">
        <el-icon class="is-loading" :size="32" color="#409eff">
          <Loading />
        </el-icon>
        <p>加载中...</p>
      </div>

      <div v-else-if="notifications.length === 0" class="empty-container">
        <el-empty description="暂无系统通知" />
      </div>

      <div v-else class="notification-list">
        <div 
          v-for="notification in notifications" 
          :key="notification.id" 
          class="notification-item"
          :class="{ 'unread': !notification.is_read }"
          @click="handleNotificationClick(notification)"
        >
          <div class="notification-header">
            <div class="notification-title">
              <span v-if="!notification.is_read" class="unread-dot"></span>
              {{ notification.title }}
            </div>
            <div class="notification-time">{{ formatTime(notification.created_at) }}</div>
          </div>
          <div class="notification-content">
            {{ notification.content }}
          </div>
          <div class="notification-footer" v-if="notification.type">
            <el-tag :type="getNotificationType(notification.type)" size="small">
              {{ getNotificationTypeText(notification.type) }}
            </el-tag>
          </div>
        </div>
      </div>
    </div>
  </div>
</template>

<script setup>
import { ref, computed, onMounted, onUnmounted } from 'vue'
import { useRouter } from 'vue-router'
import { ElMessage, ElMessageBox } from 'element-plus'
import { ArrowLeft, Loading, MoreFilled, CircleCheck, Delete } from '@element-plus/icons-vue'
import { wsManager } from '@/utils/websocket'
import { useNotificationStore } from '@/stores/notification'
import axios from 'axios'

// API 基础 URL
const API_BASE_URL = 'http://127.0.0.1:8000'

const router = useRouter()
const notificationStore = useNotificationStore()
const loading = ref(false)
const notifications = ref([])
let unsubscribeWs = null // WebSocket 取消监听函数
let notificationId = 1000 // 通知ID计数器

// 🔹 localStorage 配置
const STORAGE_KEY = 'system_notifications'
const MAX_NOTIFICATIONS = 100 // 最多保留 100 条通知
const MAX_DAYS = 30 // 保留 30 天内的通知

// 🔹 从 localStorage 加载通知
const loadNotificationsFromStorage = () => {
  try {
    const stored = localStorage.getItem(STORAGE_KEY)
    if (stored) {
      const data = JSON.parse(stored)
      
      // 🧹 清理过期通知（超过 MAX_DAYS 天）
      const now = new Date()
      const filteredData = data.filter(notification => {
        const createdAt = new Date(notification.created_at)
        const daysDiff = (now - createdAt) / (1000 * 60 * 60 * 24)
        return daysDiff <= MAX_DAYS
      })
      
      notifications.value = filteredData
      
      // 更新 notificationId 计数器，确保新通知 ID 不重复
      if (filteredData.length > 0) {
        const maxId = Math.max(...filteredData.map(n => n.id))
        notificationId = maxId + 1
      }
      
      // 如果清理后数量变少了，立即保存
      if (filteredData.length < data.length) {
        saveNotificationsToStorage()
      }
    }
  } catch (error) {
    console.error('[NotificationView] 加载本地通知失败:', error)
  }
}

// 🔹 保存通知到 localStorage（自动限制数量）
const saveNotificationsToStorage = () => {
  try {
    // 🎯 只保留最新的 MAX_NOTIFICATIONS 条
    const toSave = notifications.value.slice(0, MAX_NOTIFICATIONS)
    localStorage.setItem(STORAGE_KEY, JSON.stringify(toSave))
    
    // 如果实际通知数超过限制，同步更新内存中的数据
    if (notifications.value.length > MAX_NOTIFICATIONS) {
      notifications.value = toSave
    }
  } catch (error) {
    console.error('[NotificationView] 保存通知到本地失败:', error)
  }
}

// 计算未读数量
const unreadCount = computed(() => {
  return notifications.value.filter(n => !n.is_read).length
})

// WebSocket 消息处理
const handleWebSocketMessage = (data) => {
  console.log('[NotificationView] 📨 收到消息:', data)
  
  // 跳过连接状态消息
  if (data.type === 'connected' || data.type === 'disconnected') {
    return
  }
  
  // 🎯 优先处理后端定时任务发送的通知格式: {type, title, content, status}
  if (data.type && data.title && data.content) {
    // 添加到通知列表
    const notification = {
      id: notificationId++,
      title: data.title,
      content: data.content,
      type: data.type,
      is_read: false,
      created_at: new Date().toISOString(),
      status: data.status || 1
    }
    
    // 在列表顶部添加新通知
    notifications.value.unshift(notification)
    
    // 💾 保存到 localStorage
    saveNotificationsToStorage()
    
    // 显示吐司提示
    ElMessage.success({
      message: data.content,
      duration: 5000
    })
    return
  }
  
  // 🎯 兼容后端查询接口格式: {code: 200, msg: "...", data: {...}}
  if (data.code === 200 && data.msg) {
    // 只处理特定的认证消息
    if (data.msg === '用户已认证' && data.data) {
      const title = '🎉 实名认证成功'
      const userName = data.data.name || '用户'
      const content = `恭喜${userName}，您的实名认证已通过审核！`
      
      // 添加到通知列表
      const notification = {
        id: notificationId++,
        title: title,
        content: content,
        type: 'success',
        is_read: false,
        created_at: new Date().toISOString(),
        status: data.data?.is_real || 1
      }
      
      // 在列表顶部添加新通知
      notifications.value.unshift(notification)
      
      // 显示吐司提示
      ElMessage.success({
        message: content,
        duration: 5000
      })
      return
    }
  }
  
  // 🎯 兼容其他旧格式
  if (data.type === 'success' || data.message) {
    const notification = {
      id: notificationId++,
      title: data.title || '系统通知',
      content: data.content || data.message || '您有一条新通知',
      type: data.type || 'system',
      is_read: false,
      created_at: new Date().toISOString(),
      status: data.status || 0
    }
    
    // 在列表顶部添加新通知
    notifications.value.unshift(notification)
    
    // 显示吐司提示
    ElMessage.success({
      message: notification.content,
      duration: 3000
    })
  }
}

onMounted(async () => {
  // 检查是否已登录
  const userToken = localStorage.getItem('token')
  if (!userToken) {
    ElMessage.error('请先登录')
    router.push('/login')
    return
  }
  
  // 🔴 进入通知页面时，清除未读数（用户已经"看到"通知列表了）
  notificationStore.clearUnread()
  
  // 获取用户ID
  const storedUserInfo = localStorage.getItem('userInfo')
  if (storedUserInfo) {
    const userInfoData = JSON.parse(storedUserInfo)
    const userId = userInfoData.id
    
    if (userId) {
      // 初始化 WebSocket 连接
      wsManager.init(userId)
      unsubscribeWs = wsManager.onMessage(handleWebSocketMessage)
    }
  }
  
  // 🔄 先从 localStorage 加载（快速显示）
  loadNotificationsFromStorage()
  
  // 📡 然后从服务器加载最新数据
  loadNotifications()
})

// 加载通知列表（从后端 API）
const loadNotifications = async () => {
  loading.value = true
  try {
    const token = localStorage.getItem('token')
    const response = await axios.get(`${API_BASE_URL}/api/notifications`, {
      headers: {
        'Authorization': `Bearer ${token}`
      },
      params: {
        page: 1,
        page_size: 100  // 获取最近100条
      }
    })
    
    if (response.data && response.data.items) {
      // 合并服务器数据和本地数据
      const serverNotifications = response.data.items.map(item => ({
        id: item.id,
        title: item.title,
        content: item.content,
        type: item.type,
        is_read: item.is_read,
        created_at: item.created_at,
        status: item.status
      }))
      
      // 使用服务器数据覆盖本地数据
      notifications.value = serverNotifications
      
      // 更新 localStorage
      saveNotificationsToStorage()
      
      console.log('[NotificationView] ✅ 从服务器加载通知成功:', response.data.total, '条')
    }
    
    loading.value = false
  } catch (error) {
    loading.value = false
    console.error('[NotificationView] ⚠️  从服务器加载通知失败:', error)
    
    // 如果是 401 未授权，清除登录信息
    if (error.response && error.response.status === 401) {
      ElMessage.error('登录已过期，请重新登录')
      localStorage.removeItem('token')
      localStorage.removeItem('userInfo')
      router.push('/login')
      return
    }
    
    // 如果服务器请求失败，继续使用本地数据
    console.log('[NotificationView] 使用本地缓存数据')
  }
}

// 格式化时间
const formatTime = (timeStr) => {
  const time = new Date(timeStr)
  const now = new Date()
  const diff = now - time
  
  const minute = 60 * 1000
  const hour = 60 * minute
  const day = 24 * hour
  
  if (diff < minute) {
    return '刚刚'
  } else if (diff < hour) {
    return `${Math.floor(diff / minute)}分钟前`
  } else if (diff < day) {
    return `${Math.floor(diff / hour)}小时前`
  } else if (diff < 7 * day) {
    return `${Math.floor(diff / day)}天前`
  } else {
    return time.toLocaleDateString('zh-CN', { 
      year: 'numeric', 
      month: '2-digit', 
      day: '2-digit' 
    })
  }
}

// 获取通知类型标签类型
const getNotificationType = (type) => {
  const typeMap = {
    'system': 'info',
    'success': 'success',
    'warning': 'warning',
    'error': 'danger'
  }
  return typeMap[type] || 'info'
}

// 获取通知类型文本
const getNotificationTypeText = (type) => {
  const textMap = {
    'system': '系统通知',
    'success': '审核通知',
    'warning': '重要提醒',
    'error': '异常通知'
  }
  return textMap[type] || '通知'
}

// 点击通知项
const handleNotificationClick = async (notification) => {
  if (!notification.is_read) {
    try {
      // 调用 API 标记为已读
      const token = localStorage.getItem('token')
      await axios.patch(
        `${API_BASE_URL}/api/notifications/${notification.id}/read`,
        {},
        {
          headers: {
            'Authorization': `Bearer ${token}`
          }
        }
      )
      
      // 更新本地状态
      notification.is_read = true
      saveNotificationsToStorage()
    } catch (error) {
      console.error('[NotificationView] 标记已读失败:', error)
    }
  }
  
  // TODO: 如果需要详情页，可以实现
  // router.push(`/notification/${notification.id}`)
}

// 下拉菜单命令处理
const handleCommand = async (command) => {
  if (command === 'markAllRead') {
    await markAllAsRead()
  } else if (command === 'clearAll') {
    await clearAllNotifications()
  }
}

// 全部标记为已读
const markAllAsRead = async () => {
  try {
    const token = localStorage.getItem('token')
    await axios.patch(
      `${API_BASE_URL}/api/notifications/mark-all-read`,
      {},
      {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      }
    )
    
    // 更新本地状态
    notifications.value.forEach(n => {
      n.is_read = true
    })
    saveNotificationsToStorage()
    
    ElMessage.success('已全部标记为已读')
  } catch (error) {
    console.error('[NotificationView] 标记失败:', error)
    ElMessage.error('操作失败')
  }
}

// 清空所有通知
const clearAllNotifications = async () => {
  try {
    await ElMessageBox.confirm(
      '确定要清空所有通知吗？此操作不可恢复。',
      '确认清空',
      {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning',
      }
    )
    
    const token = localStorage.getItem('token')
    await axios.delete(
      `${API_BASE_URL}/api/notifications/clear-all`,
      {
        headers: {
          'Authorization': `Bearer ${token}`
        }
      }
    )
    
    // 清空本地数据
    notifications.value = []
    saveNotificationsToStorage()
    
    ElMessage.success('已清空所有通知')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('[NotificationView] 清空通知失败:', error)
      ElMessage.error('清空通知失败')
    }
  }
}

// 返回上一页
const goBack = () => {
  router.back()
}

// 组件卸载时清理监听器（但不断开连接，因为其他页面可能还需要）
onUnmounted(() => {
  console.log('[NotificationView] 组件卸载，清理 WebSocket 监听')
  if (unsubscribeWs) {
    unsubscribeWs()
  }
  // 不断开连接，保持 WebSocket 活跃
  // wsManager.disconnect()
})
</script>

<style scoped>
.page-container {
  min-height: 100vh;
  background-color: #f5f7fa;
}

.header {
  background: white;
  padding: 0 16px;
  height: 56px;
  display: flex;
  align-items: center;
  justify-content: space-between;
  box-shadow: 0 1px 4px rgba(0, 0, 0, 0.08);
  position: sticky;
  top: 0;
  left: 0;
  right: 0;
  z-index: 100;
}

.back-icon {
  color: #606266;
  cursor: pointer;
  transition: color 0.3s;
  margin-right: 12px;
}

.back-icon:hover {
  color: #409eff;
}

.header h1 {
  flex: 1;
  margin: 0;
  font-size: 18px;
  font-weight: 600;
  color: #303133;
}

.header-right {
  display: flex;
  align-items: center;
}

.more-actions {
  font-size: 20px;
  color: #606266;
  cursor: pointer;
  transition: color 0.3s;
  display: flex;
  align-items: center;
  padding: 4px;
}

.more-actions:hover {
  color: #409eff;
}

.mark-all-read {
  font-size: 14px;
  color: #409eff;
  cursor: pointer;
  transition: opacity 0.3s;
}

.mark-all-read:hover {
  opacity: 0.7;
}

.content {
  padding: 0 0 80px;
  min-height: calc(100vh - 56px);
}

.loading-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  justify-content: center;
  padding: 60px 0;
  color: #909399;
}

.loading-container p {
  margin-top: 12px;
  font-size: 14px;
}

.empty-container {
  padding: 60px 0;
}

.notification-list {
  background: white;
}

.notification-item {
  padding: 16px;
  border-bottom: 1px solid #f0f0f0;
  cursor: pointer;
  transition: background-color 0.3s;
  position: relative;
}

.notification-item:hover {
  background-color: #f9f9f9;
}

.notification-item.unread {
  background-color: #f0f7ff;
}

.notification-item.unread:hover {
  background-color: #e6f2ff;
}

.notification-header {
  display: flex;
  justify-content: space-between;
  align-items: flex-start;
  margin-bottom: 8px;
}

.notification-title {
  flex: 1;
  font-size: 15px;
  font-weight: 600;
  color: #303133;
  display: flex;
  align-items: center;
  line-height: 1.5;
}

.unread-dot {
  display: inline-block;
  width: 8px;
  height: 8px;
  background-color: #f56c6c;
  border-radius: 50%;
  margin-right: 8px;
  flex-shrink: 0;
}

.notification-time {
  font-size: 12px;
  color: #909399;
  white-space: nowrap;
  margin-left: 12px;
}

.notification-content {
  font-size: 14px;
  color: #606266;
  line-height: 1.6;
  margin-bottom: 8px;
}

.notification-footer {
  display: flex;
  align-items: center;
  justify-content: flex-end;
}
</style>

